<?php

// PHP雪里开轻量级报修系统 V1.0Beta
// 演示地址: http://baoxiu.chalide.cn
// 更新关注: /weivote
// 文件路径: sys/lius.php
// 文件大小: 19151 字节
// 最后修改时间: 2025-05-21 17:32:33
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权

/**
 * 本文件功能：系统管理员-学生管理
 * 版权声明：保留发行权和署名权
 * 作者信息：功能反馈:15058593138@qq.com(手机号同微信)
 */

// 处理AJAX请求
if (isset($_GET['act'])) {
    switch ($_GET['act']) {
        case 'save':
            // 保存学生/用户信息
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            $xuehao = isset($_POST['xuehao']) ? trim($_POST['xuehao']) : '';
            $realname = isset($_POST['realname']) ? trim($_POST['realname']) : '';
            $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
            $type = isset($_POST['type']) ? trim($_POST['type']) : '学生';
            $status = isset($_POST['status']) ? intval($_POST['status']) : 1;
            $remark = isset($_POST['remark']) ? trim($_POST['remark']) : '';
            
            // 验证数据
            if (empty($xuehao)) {
                json_error('请输入学号/工号');
            }
            
            if (empty($realname)) {
                json_error('请输入姓名');
            }
            
            if (empty($phone)) {
                json_error('请输入电话');
            }
            
            if (!in_array($type, ['学生', '后勤', '系统'])) {
                json_error('无效的用户类型');
            }
            
            // 检查学号/工号是否已存在
            $check_condition = "xuehao = '{$mysqli->real_escape_string($xuehao)}'";
            if ($id > 0) {
                $check_condition .= " AND id != {$id}";
            }
            
            $check = $db->getOne('stux', $check_condition);
            if ($check) {
                json_error('学号/工号已存在');
            }
            
            // 准备数据
            $data = [
                'xuehao' => $xuehao,
                'realname' => $realname,
                'phone' => $phone,
                'type' => $type,
                'status' => $status,
                'remark' => $remark
            ];
            
            // 新增用户需要设置默认密码
            if ($id <= 0) {
                $data['password'] = md5($xuehao); // 默认密码与学号/工号相同
                $data['create_time'] = date('Y-m-d H:i:s');
            }
            
            // 保存数据
            if ($id > 0) {
                // 更新
                $result = $db->update('stux', $data, "id = {$id}");
                $msg = '更新成功';
            } else {
                // 新增
                $result = $db->insert('stux', $data);
                $msg = '添加成功';
            }
            
            if ($result) {
                json_success($msg);
            } else {
                json_error('操作失败: ' . $mysqli->error);
            }
            break;
            
        case 'delete':
            // 删除用户
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            
            if ($id <= 0) {
                json_error('无效的用户ID');
            }
            
            // 检查是否为当前登录用户
            if ($id == $_SESSION['user_id']) {
                json_error('不能删除当前登录用户');
            }
            
            // 检查是否有关联的报修记录
            $repairs = $db->getOne('bxiu', "user_id = {$id}");
            if ($repairs) {
                json_error('该用户有关联的报修记录，不能删除');
            }
            
            // 删除用户
            $result = $db->delete('stux', "id = {$id}");
            
            if ($result) {
                json_success('删除成功');
            } else {
                json_error('删除失败: ' . $mysqli->error);
            }
            break;
            
        case 'reset':
            // 重置密码
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            
            if ($id <= 0) {
                json_error('无效的用户ID');
            }
            
            // 获取用户信息
            $user = $db->getOne('stux', "id = {$id}");
            if (!$user) {
                json_error('用户不存在');
            }
            
            // 重置密码为学号/工号
            $new_password = md5($user['xuehao']);
            $result = $db->update('stux', ['password' => $new_password], "id = {$id}");
            
            if ($result) {
                json_success('密码已重置为学号/工号');
            } else {
                json_error('密码重置失败: ' . $mysqli->error);
            }
            break;
            
        case 'status':
            // 修改状态
            $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
            $status = isset($_POST['status']) ? intval($_POST['status']) : 0;
            
            if ($id <= 0) {
                json_error('无效的用户ID');
            }
            
            // 检查是否为当前登录用户
            if ($id == $_SESSION['user_id']) {
                json_error('不能修改当前登录用户的状态');
            }
            
            // 更新状态
            $result = $db->update('stux', ['status' => $status], "id = {$id}");
            
            if ($result) {
                json_success('状态修改成功');
            } else {
                json_error('状态修改失败: ' . $mysqli->error);
            }
            break;
            
        case 'get':
            // 获取用户信息
            $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
            
            if ($id <= 0) {
                json_error('无效的用户ID');
            }
            
            $user = $db->getOne('stux', "id = {$id}");
            
            if ($user) {
                // 移除密码字段
                unset($user['password']);
                json_success('获取成功', $user);
            } else {
                json_error('用户不存在');
            }
            break;
    }
    exit;
}

// 包含头部
include './inc/head.php';

// 获取查询参数
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$page_size = 10;

// 构建查询条件
$condition = "1=1";

if (!empty($keyword)) {
    $keyword = $mysqli->real_escape_string($keyword);
    $condition .= " AND (xuehao LIKE '%{$keyword}%' OR realname LIKE '%{$keyword}%' OR phone LIKE '%{$keyword}%')";
}

if (!empty($type)) {
    $type = $mysqli->real_escape_string($type);
    $condition .= " AND type = '{$type}'";
}

if ($status !== '') {
    $status = intval($status);
    $condition .= " AND status = {$status}";
}

// 获取分页数据
$pager = $db->pager('stux', $condition, '*', 'id DESC', $page, $page_size);
$users = $pager['data'];
?>
<div class="card">
    <div class="card-header">
        <form class="search-form" method="get" action="">
            <input type="hidden" name="do" value="lius">
            <div class="search-container">
    <h2 class="page-title">用户管理</h2>
                <div class="search-item">
                    <input type="text" class="form-control" name="keyword" placeholder="搜索学号/姓名/电话" value="<?php echo htmlspecialchars($keyword); ?>">
                </div>
                <div class="search-item">
                    <select class="form-control" name="type">
                        <option value="">全部类型</option>
                        <option value="学生" <?php echo $type == '学生' ? 'selected' : ''; ?>>学生</option>
                        <option value="后勤" <?php echo $type == '后勤' ? 'selected' : ''; ?>>后勤</option>
                        <option value="系统" <?php echo $type == '系统' ? 'selected' : ''; ?>>系统</option>
                    </select>
                </div>
                <div class="search-item">
                    <select class="form-control" name="status">
                        <option value="">全部状态</option>
                        <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>正常</option>
                        <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>禁用</option>
                    </select>
                </div>
                <div class="search-item">
                    <button type="submit" class="btn btn-primary">搜索</button>
                </div>
              <button type="button" class="btn btn-primary" onclick="showUserForm()">添加用户</button>
            </div>
        </form>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>学号/工号</th>
                        <th>姓名</th>
                        <th>电话</th>
                        <th>类型</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($users)): ?>
                    <tr>
                        <td colspan="8" class="text-center">暂无记录</td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?php echo $user['id']; ?></td>
                        <td><?php echo htmlspecialchars($user['xuehao']); ?></td>
                        <td><?php echo htmlspecialchars($user['realname']); ?></td>
                        <td><?php echo htmlspecialchars($user['phone']); ?></td>
                        <td><?php echo htmlspecialchars($user['type']); ?></td>
                        <td>
                            <?php if ($user['status'] == 1): ?>
                            <span class="badge badge-success">正常</span>
                            <?php else: ?>
                            <span class="badge badge-danger">禁用</span>
                            <?php endif; ?>
                        </td>
                        <td><?php echo format_date($user['create_time']); ?></td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="editUser(<?php echo $user['id']; ?>)">编辑</button>
                            <button type="button" class="btn btn-sm btn-info" onclick="resetPassword(<?php echo $user['id']; ?>)">重置密码</button>
                            
                            <?php if ($user['id'] != $_SESSION['user_id']): ?>
                                <?php if ($user['status'] == 1): ?>
                                <button type="button" class="btn btn-sm btn-warning" onclick="changeStatus(<?php echo $user['id']; ?>, 0)">禁用</button>
                                <?php else: ?>
                                <button type="button" class="btn btn-sm btn-success" onclick="changeStatus(<?php echo $user['id']; ?>, 1)">启用</button>
                                <?php endif; ?>
                                
                                <button type="button" class="btn btn-sm btn-danger" onclick="deleteUser(<?php echo $user['id']; ?>)">删除</button>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($pager['total_pages'] > 1): ?>
        <div class="pagination-container">
            <?php echo pagination($pager['page'], $pager['total_pages'], "?do=lius&keyword=" . urlencode($keyword) . "&type=" . urlencode($type) . "&status=" . urlencode($status)); ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- 用户表单模态框 -->
<div id="userFormModal" class="modal" style="display: none;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="formTitle">添加用户</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="hideUserForm()">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <input type="hidden" id="user_id" name="id" value="0">
                    
                    <div class="form-group">
                        <label for="xuehao">学号/工号</label>
                        <input type="text" class="form-control" id="xuehao" name="xuehao" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="realname">姓名</label>
                        <input type="text" class="form-control" id="realname" name="realname" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="phone">电话</label>
                        <input type="text" class="form-control" id="phone" name="phone" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="type">用户类型</label>
                        <select class="form-control" id="type" name="type">
                            <option value="学生">学生</option>
                            <option value="后勤">后勤</option>
                            <option value="系统">系统</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="status">状态</label>
                        <select class="form-control" id="status" name="status">
                            <option value="1">正常</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="remark">备注</label>
                        <textarea class="form-control" id="remark" name="remark" rows="3"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="hideUserForm()">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>
</div>

<script>
// 显示用户表单
function showUserForm() {
    // 重置表单
    document.getElementById('userForm').reset();
    document.getElementById('user_id').value = '0';
    document.getElementById('formTitle').textContent = '添加用户';
    
    // 显示模态框
    document.getElementById('userFormModal').style.display = 'block';
}

// 隐藏用户表单
function hideUserForm() {
    document.getElementById('userFormModal').style.display = 'none';
}

// 编辑用户
function editUser(id) {
    // 获取用户信息
    ajax('?do=lius&act=get&id=' + id, {}, function(response) {
        if (response.status === 'success') {
            var user = response.data;
            
            // 填充表单
            document.getElementById('user_id').value = user.id;
            document.getElementById('xuehao').value = user.xuehao;
            document.getElementById('realname').value = user.realname;
            document.getElementById('phone').value = user.phone;
            document.getElementById('type').value = user.type;
            document.getElementById('status').value = user.status;
            document.getElementById('remark').value = user.remark || '';
            
            // 更新标题
            document.getElementById('formTitle').textContent = '编辑用户';
            
            // 显示模态框
            document.getElementById('userFormModal').style.display = 'block';
        } else {
            showToast(response.msg, 'error');
        }
    }, 'GET');
}

// 保存用户
function saveUser() {
    var formData = getFormData('userForm');
    
    // 简单验证
    if (!formData.xuehao) {
        showToast('请输入学号/工号', 'warning');
        return;
    }
    
    if (!formData.realname) {
        showToast('请输入姓名', 'warning');
        return;
    }
    
    if (!formData.phone) {
        showToast('请输入电话', 'warning');
        return;
    }
    
    // 发送请求
    ajax('?do=lius&act=save', formData, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            hideUserForm();
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 删除用户
function deleteUser(id) {
    if (!confirm('确定要删除该用户吗？此操作不可恢复！')) {
        return;
    }
    
    ajax('?do=lius&act=delete', {id: id}, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 重置密码
function resetPassword(id) {
    if (!confirm('确定要将该用户的密码重置为学号/工号吗？')) {
        return;
    }
    
    ajax('?do=lius&act=reset', {id: id}, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 修改状态
function changeStatus(id, status) {
    var statusText = status === 1 ? '启用' : '禁用';
    
    if (!confirm('确定要' + statusText + '该用户吗？')) {
        return;
    }
    
    ajax('?do=lius&act=status', {id: id, status: status}, function(response) {
        if (response.status === 'success') {
            showToast(response.msg, 'success');
            
            // 刷新页面
            setTimeout(function() {
                window.location.reload();
            }, 1500);
        } else {
            showToast(response.msg, 'error');
        }
    });
}

// 模态框事件处理
document.addEventListener('click', function(event) {
    var modal = document.getElementById('userFormModal');
    if (event.target === modal) {
        hideUserForm();
    }
});
</script>
